package com.wdb007.venus.wss.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wdb007.venus.svc.biz.manager.ConfigInfoManager;
import com.wdb007.venus.svc.facade.QrCodeService;
import com.wdb007.venus.svc.facade.qrcode.model.QrCodeCurrentInfoDTO;
import com.wdb007.venus.wss.channelgroup.BookCaseChannelGroups;
import com.wdb007.venus.wss.constants.PushActionEnum;
import com.wdb007.venus.wss.service.WebSocketServerService;

import io.netty.channel.ChannelHandlerContext;

@Service("policiesQrCodeService")
public class WsPoliciesQrCodeService implements WebSocketServerService {

	private static Logger logger = LoggerFactory.getLogger(WsPoliciesQrCodeService.class);
	
	@Autowired
	private QrCodeService qrCodeService;
	
	@Autowired
	private ConfigInfoManager configInfoManager;
	
	@Override
	public String doService(ChannelHandlerContext ctx, String request) throws Exception {
		
		JSONObject jsonObj = JSON.parseObject(request);
		String bookCaseId = jsonObj.getString("bookCaseId");
		generateQrCode(bookCaseId);
		return null;
	}

	
	
	private void generateQrCode(String bookCaseId) {
		String qrcode_prefix = configInfoManager.getValue("qrcode_prefix");
		
		String shortKey = qrCodeService.saveQrCode(bookCaseId);
		String qrcode_text = qrcode_prefix +"bookcaseId="+ shortKey;
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("action", PushActionEnum.policies_qrcode.name());
		jsonObj.put("qrcodeText", qrcode_text);
		BookCaseChannelGroups.broadcast(bookCaseId, jsonObj.toJSONString());
		logger.info("给书柜[{}]下发二维码[{}]完成", bookCaseId, qrcode_text);
	}

	public void schedulePolicies() {
		Integer policiesInterval = Integer.valueOf(configInfoManager.getValue("policies_interval"));
		List<QrCodeCurrentInfoDTO> list = qrCodeService.list(policiesInterval);
		if(CollectionUtils.isEmpty(list)) {
			return ;
		}
		for(QrCodeCurrentInfoDTO info : list) {
			generateQrCode(info.getBookcaseId());
		}
	}
	
	public void removeQrCodePoliciesLog() {
		qrCodeService.removeQrCodePoliciesLog();
	}
}
